<template>
	
	<div>
		<el-dialog
			v-model="visible"
			:title="title"
			destroy-on-close
			append-to-body
			width="550px"
			class="editor-dialog-c"
			draggable
			:close-on-click-modal="false"
		>
		
		<el-form
		  ref="formRef"
		  :model="formData"
		  :rules="formRules"
		  label-width="100px"
		>
			
			<el-form-item label="类型" prop="type">
			  <el-radio-group v-model="formData.type" >
				<el-radio-button value="attribute">属性</el-radio-button>
				<el-radio-button value="method">方法</el-radio-button>
			    <el-radio-button value="event">事件</el-radio-button>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="名称" prop="name">
			  <el-input v-model="formData.name" placeholder="请输入名称" />
			</el-form-item>
			
			<el-form-item label="标识符" prop="identifier">
			  <el-input v-model="formData.identifier" placeholder="请输入标识符" />
			</el-form-item>
			
			<el-form-item label="是否自定义" prop="isCustom">
			  <el-radio-group v-model="formData.isCustom" id="isCustom" >
			    <el-radio :value="'1'">是</el-radio>
			    <el-radio :value="'0'">否</el-radio>
			  </el-radio-group>
			</el-form-item>
			
			<el-form-item label="自定义识符" prop="customIdentifier"  v-if="formData.isCustom=='1'">
			  <el-input v-model="formData.customIdentifier" placeholder="业务码" />
			</el-form-item>
			
			<el-form-item label="业务码" prop="code">
			  <el-input v-model="formData.code" placeholder="业务码" />
			</el-form-item>

			<!-- 输入参数 -->
			<el-form-item v-if="formData.type=='method' || formData.type=='attribute'" label="输入参数" prop="inputParams">
				<div  v-for="(item, index) in inputParams" :key="index" class="json-item">
					<div class="title">
						{{ item.name+" - "+item.identifier }}
					</div>
					<div class="opear">
						<el-button type="primary" :icon="Edit" link @click="editInputParameter(item,index)"/>
						<el-button type="warning" :icon="DocumentCopy" link @click="copyInputParameter(item,index)" />
						<el-button type="info" :icon="SortDown" link @click="downInputParameter(item,index)"/>
						<el-button type="info" :icon="SortUp" link @click="upInputParameter(item,index)"/>
						<el-button type="danger" :icon="Delete" link @click="deleteInputParameter(index)"/>
					</div>
				</div>
				<div>
					<el-button type="success" :icon="Plus" link @click="addInputParameter">增加参数</el-button>
					<el-button type="warning" :icon="Download" link @click="addInputParameterByJson">json数据导入</el-button>
					<!-- <el-button type="danger" :icon="Notebook" link @click="addInputParameterByDb">数据库</el-button> -->
				</div>
			</el-form-item>

			<!-- 输出参数 -->
			<el-form-item v-if="formData.type=='method' || formData.type=='event' " label="输出参数" prop="outputParams">
				<div  v-for="(item, index) in outputParams" :key="index" class="json-item">
					<div class="title">
						{{ item.name+" - "+item.identifier }}
					</div>
					<div class="opear">
						<el-button type="primary" :icon="Edit" link @click="editOutParameter(item,index)"/>
						<el-button type="warning" :icon="DocumentCopy" link @click="copyOutParameter(item,index)" />
						<el-button type="info" :icon="SortDown" link @click="downOutParameter(item,index)"/>
						<el-button type="info" :icon="SortUp" link @click="upOutParameter(item,index)"/>
						<el-button type="danger" :icon="Delete" link @click="deleteOutParameter(index)"/>
					</div>
				</div>
				<div>
					<el-button type="success" :icon="Plus" link @click="addOutParameter">增加参数</el-button>
					<el-button type="warning" :icon="Download" link @click="addOutParameterByJson">json数据导入</el-button>
					<!-- <el-button type="danger" :icon="Notebook" link @click="addOutParameterByDb">数据库</el-button> -->
				</div>
			</el-form-item>
			
			<el-form-item label="序号" prop="sort">
			  <el-input-number
				style="width: 100%;"
				v-model="formData.sort"
				controls-position="right"
			  />
			</el-form-item>
			
			
		</el-form>
		
		<template #footer>
		  <div class="dialog-footer">
			<el-button color="#626aef" @click="submitForm"  :loading="loading" v-hasPerm="['ue:thingmodel:saveFun']">确 定</el-button>
			<el-button color="#1e1e1e" @click="closed" :loading="loading">取 消</el-button>
		  </div>
		</template>
		
		</el-dialog>
		<FieldPane 
		      v-if="parameterPane.visible"
		      :properties="parameterPane"
		      @backParameter="receiveParameter"
		      @closed="closeField"
		></FieldPane>
		
		<ImportParameterDialog
			ref="importParameterDialogRef"
			@closeDialog="closeImportParameterDialog"
		>
		</ImportParameterDialog>
		
		<DbParameterDialog
			ref="dbParameterDialogRef"
			@closeDialog="closeDbParameterDialog"
		>
		</DbParameterDialog>
		
	</div>
</template>
<script lang="ts" setup>
	import { Plus,Delete, Edit, SortUp, SortDown, DocumentCopy,Download ,Notebook} from '@element-plus/icons-vue'
	import FieldPane from "./FieldPane.vue";
	import ImportParameterDialog from "./ImportParameterDialog.vue";
	import DbParameterDialog from "./DbParameterDialog.vue";
	
	import type {FormRules } from 'element-plus'
	
	import { saveThingmodelFun} from "@/api/sys/thingmodel";
	
	const importParameterDialogRef=ref();
	const dbParameterDialogRef=ref();
	
	const formRef=ref();
	const visible=ref(false)
	const title=ref<any>("")
	const props=defineProps({
		visible:Boolean,
		title:String,
		data:Object
	})
	const emits = defineEmits(['closed'])
	const formData=ref<any>({})
	const formRules=reactive<FormRules>({
	  name: [{ required: true, message: "参数必填", trigger: "blur" }],
	  identifier: [{ required: true, message: "参数必填", trigger: "blur" }],
	  isCustom: [{ required: true, message: "参数必填", trigger: "blur" }],
	  type: [{ required: true, message: "参数必填", trigger: "blur" }],
	});
	
	
	const loading=ref<boolean>(false);
	const currentParameter=ref<any>();
	const inputParams= ref<any>([]);
	const outputParams= ref<any>([]);
	const json= ref<any>([]);
	const parameterPane= ref<any>({
		visible: false,
		title: '添加字段',
		data: {}
	});
	
	watch(props,() => {
			visible.value=props.visible
			title.value=props.title
			formData.value.thingmodelId=props.data?.thingmodelId
			formData.value.id=props.data?.id
			formData.value.name=props.data?.name
			formData.value.code=props.data?.code
			formData.value.identifier=props.data?.identifier
			formData.value.type=props.data?.type
			formData.value.sort=props.data?.sort
			formData.value.isCustom=props.data?.isCustom
			formData.value.customIdentifier=props.data?.customIdentifier
			if(props.data && props.data.inputData){
				inputParams.value=JSON.parse(props.data?.inputData)
			}
			if(props.data && props.data.outputData){
				outputParams.value=JSON.parse(props.data?.outputData)
			}
		},
	    { immediate: true, deep: true },
	)

	const addExtendParameter=(current:any)=> {
	  currentParameter.value = current
	  parameterPane.value.visible = true
	  parameterPane.value.data = undefined
	  
	  if (currentParameter.value === '0') {
			parameterPane.value.isShowStructAndArray = false
	  } else if (currentParameter.value === '1') {
			parameterPane.value.isShowStructAndArray = true
	  } else if (currentParameter.value === '2') {
			parameterPane.value.isShowStructAndArray = true
	  }
	}
	
   const addInputParameter=()=> {
      addExtendParameter('1')
    }
    const editInputParameter= (item:any, index:any)=> {
      currentParameter.value = '1'
      parameterPane.value.visible = true
      parameterPane.value.data = item
      //console.log('item=', item)
      parameterPane.value.index = index
    }
	
	const copyInputParameter=(item:any,index:any)=>{
		let newItem=JSON.parse(JSON.stringify(item))
		newItem.name=newItem.name+"_copy"
		newItem.identifier=newItem.identifier+"_copy"
		inputParams.value.splice(index+1,0,newItem);
	}
	
	const upInputParameter=(item:any,index:any)=>{
		inputParams.value.splice(index, 1)
		inputParams.value.splice(index-1,0,item);
	}
	
	const downInputParameter=(item:any,index:any)=>{
		inputParams.value.splice(index, 1)
		inputParams.value.splice(index+1,0,item);
	}
	
    const deleteInputParameter=(index:any)=> {
      inputParams.value.splice(index, 1)
    }
    const addOutParameter=()=> {
      addExtendParameter('2')
    }
	
	const addInputParameterByJson=()=> {
		importParameterDialogRef.value.openDialog(formData.value,'Input');
	}
	
	const addOutParameterByJson=()=> {
		importParameterDialogRef.value.openDialog(formData.value,'Out');
	}
	
	const closeImportParameterDialog=(type:string,json:any)=>{
		if(json){
			if(type=='Input'){
				inputParams.value=json
			}
			else{
				outputParams.value=json
			}
		}
	}
	
	const addInputParameterByDb=()=> {
		dbParameterDialogRef.value.openDialog(formData.value,'Input');
	}
	
	const addOutParameterByDb=()=> {
		dbParameterDialogRef.value.openDialog(formData.value,'Out');
	}
	
	const closeDbParameterDialog=(type:string,json:any)=>{
		if(json){
			if(type=='Input'){
				inputParams.value=json
			}
			else{
				outputParams.value=json
			}
		}
	}
	
    const editOutParameter=(item:any, index:any)=> {
      currentParameter.value = '2'
      parameterPane.value.visible = true
      parameterPane.value.data = item
      parameterPane.value.index = index
    }
	
	const copyOutParameter=(item:any,index:any)=>{
		let newItem=JSON.parse(JSON.stringify(item))
		newItem.name=newItem.name+"_copy"
		newItem.identifier=newItem.identifier+"_copy"
		outputParams.value.splice(index+1,0,newItem);
	}
	
	const upOutParameter=(item:any,index:any)=>{
		outputParams.value.splice(index, 1)
		outputParams.value.splice(index-1,0,item);
	}
	
	const downOutParameter=(item:any,index:any)=>{
		outputParams.value.splice(index, 1)
		outputParams.value.splice(index+1,0,item);
	}
	
    const deleteOutParameter=(index:any)=> {
      outputParams.value.splice(index, 1)
    }
	
	const closeField=()=>{
		parameterPane.value.visible = false
		parameterPane.value.data = {}
		parameterPane.value.index = undefined
		currentParameter.value = undefined
	}
	
	const receiveParameter=(parameter:any, itemIdex:any)=> {
	  if (currentParameter.value == '1') {
		if (itemIdex || typeof itemIdex === 'number') {
		  inputParams.value[itemIdex] = parameter
		} else {
		  inputParams.value.push(parameter)
		}
	  } else if (currentParameter.value === '2') {
		if (itemIdex || typeof itemIdex === 'number') {
		  outputParams.value[itemIdex] = parameter
		} else {
		  outputParams.value.push(parameter)
		}
	  } else {
		if (itemIdex || typeof itemIdex === 'number') {
		  json.value[itemIdex] = parameter
		} else {
		   json.value.push(parameter)
		}
	  }
	  parameterPane.value.isShowStructAndArray = undefined
	}
	
	const submitForm=()=>{
		formRef.value.validate((isValid: boolean) => {
		  if (isValid) {
				loading.value=true;
				formData.value.inputData=JSON.stringify(inputParams.value)
				formData.value.outputData=JSON.stringify(outputParams.value)
				saveThingmodelFun(formData.value)
				.then((res:any) => {
					ElMessage.success(res.msg);
					closed();
				})
				.catch((e:any) => {
					console.error(e)
				})
				.finally(() => {
					loading.value=false;
				});
		  }
		});
	}
	
	const closed=()=>{
	   emits('closed', false)
	}
	
	defineExpose({
	});
</script>

<style scoped>
	:deep(.el-form-item__content){
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
	}
	
	:deep(.el-row){
		width: 100%;
		margin-top: 2px;
		margin-left: 0px !important; 
		margin-right: 0px !important; 
		margin-bottom: 0px;
	}
	.json-item{
		display: flex;
		flex-direction: row;
		background-color: #2a2d3e17;
		border-radius: 4px;
		width: 100%;
		margin-bottom: 2px;
		padding-left: 5px;
		padding-right: 5px;
		color: #606266;
		>.title{
			flex: 1;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
		>.opear{
			width: 150px;
		}
	}
	
	:deep(.is-guttered){
		display: flex;
		align-content: center;
		flex-direction: row;
		align-items: center;
		height: 32px;
	}
	
	:deep(.el-radio-button) {
		--el-radio-button-checked-bg-color: #626aef;
		--el-radio-button-checked-text-color:#eee;
		--el-radio-button-checked-border-color:#626aef;
	}
	
	:deep(.el-radio-button__original-radio:checked+.el-radio-button__inne)r {
	    background-color: #626aef;
	    border-color:#626aef !important;
		box-shadow:-1px 0 0 0 var(--el-radio-button-checked-border-color,var(--el-radio-button-checked-border-color));
	}
</style>